package timmer

import (
	"World/common/logger"
	"World/db"
	"World/redis"
	"encoding/json"
	"sync"
)

var RedisLock *sync.RWMutex

func Init() {
	RedisLock = new(sync.RWMutex)
	go DoRedisTicker()
}

func DoRedisTicker() {

	RedisLock.Lock()
	for {
		if redis.GetRedisIsOpen() {
			results, err := redis.GetRedisClient().HGetAllValues(redis.GS_USERBASE_INFO)
			if err != nil {
				logger.Error("DoRedisTicker get failed err=%v", err)
				continue
			}
			for _, val := range results {
				baseinfo := new(db.UserBaseInfo)
				err = json.Unmarshal([]byte(val.(string)), baseinfo)
				if err != nil {
					logger.Error("DoRedisTicker json failed err=%v", err)
					continue
				}
				err = db.SyncUserBaseInfo(baseinfo)
				if err != nil {
					logger.Error("DoRedisTicker json failed err=%v", err)
					continue
				}

			}

			results, err = redis.GetRedisClient().HGetAllValues(redis.GS_USERDEVICE_INFO)
			if err != nil {
				logger.Error("DoRedisTicker get failed err=%v", err)
				continue
			}
			for _, val := range results {
				baseinfo := new(db.UserDeviceInfo)
				err = json.Unmarshal([]byte(val.(string)), baseinfo)
				if err != nil {
					logger.Error("DoRedisTicker json failed err=%v", err)
					continue
				}
				err = db.SyncUserDeviceInfo(baseinfo)
				if err != nil {
					logger.Error("DoRedisTicker json failed err=%v", err)
					continue
				}

			}
		}
	}
	RedisLock.Unlock()
}
